﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zhaoxi.SqlSugar.Common;
using Zhaoxi.SqlSugar.Models;

namespace Zhaoxi.SqlSugarAdvanced
{
    public class AopManager
    {
        public static void Show()
        {
            ConnectionConfig connectionConfig = new ConnectionConfig()
            {
                ConnectionString = CustomConnectionConfig.ConnectionString001,
                IsAutoCloseConnection = true,
                DbType = DbType.SqlServer
            };
            using (SqlSugarClient db = new SqlSugarClient(connectionConfig))
            {
                //修改sql语句 - 执行数序1
                db.Aop.OnExecutingChangeSql = (sql, pars) => //可以修改SQL和参数的值
                {
                    //sql=newsql
                    //foreach(var p in pars) //修改
                    return new KeyValuePair<string, SugarParameter[]>(sql, pars);
                };


                //每次Sql执行前事件 - 执行数序2
                db.Aop.OnLogExecuting = (sql, parList) =>
                {
                    //我可以在这里面写逻辑
                    Console.WriteLine("Sql语句:=================================");
                    Console.WriteLine($"{sql}");

                    Console.WriteLine("参数：=================================");
                    foreach (var para in parList)
                    {
                        Console.WriteLine($"{para.ParameterName}:{para.Value}");
                    }
                };

                //Sql执行之后 - 执行数序3
                db.Aop.OnLogExecuted = (sql, pars) =>
                {
                    //执行完了可以输出SQL执行时间 (OnLogExecutedDelegate) 
                    Console.Write("time:" + db.Ado.SqlExecutionTime.ToString());
                };

                //SQL报错：日志记录 - 执行数序4
                db.Aop.OnError = (exp) =>
                {
                    //exp.sql 这样可以拿到错误SQL，性能无影响拿到ORM带参数使用的SQL 
                    //5.0.8.2 获取无参数化 SQL  对性能有影响，特别大的SQL参数多的，调试使用
                    //UtilMethods.GetSqlString(DbType.SqlServer,exp.sql,exp.parameters) 
                    Console.WriteLine($"Sql执行报错了，异常消息：{exp.Message}");
                };


                ///当数据修改在执行前 - 执行数序5
                db.Aop.DataExecuting = (oldValue, entityInfo) =>
                {
                    /*** inset生效 ***/
                    if (entityInfo.PropertyName == "CreateTime" && entityInfo.OperationType == DataFilterType.InsertByObject)
                    {
                        entityInfo.SetValue(DateTime.Now);//修改CreateTime字段
                                                          //entityInfo有字段所有参数
                    }
                    //特性用法
                    //if(p.EntityColumnInfo.PropertyInfo.GetCustomAttribute<自定义特性>()!=null
                    // &&entityInfo.OperationType== DataFilterType.InsertByObject)
                    //5.1.3.23 更好的支持了特性
                    //p.IsAnyAttribute<特性>()
                    //p.GetAttribute<特性>()

                    /*** update生效 ***/
                    if (entityInfo.PropertyName == "UpdateTime" && entityInfo.OperationType == DataFilterType.UpdateByObject)
                    {
                        entityInfo.SetValue(DateTime.Now);//修改UpdateTime字段
                    }

                    //根据当前列修改另一列 可以么写
                    //if(当前列逻辑==XXX)
                    //var properyDate = entityInfo.EntityValue.GetType().GetProperty("Date");
                    //if(properyDate!=null)
                    //properyDate.SetValue(entityInfo.EntityValue,1);
                };

                //删除重建表- - 执行数序6
                if (db.DbMaintenance.IsAnyTable("CompanyInfo", false))
                {
                    db.DbMaintenance.DropTable<CompanyInfo>();
                }
                db.CodeFirst.InitTables<CompanyInfo>();

                CompanyInfo company = new CompanyInfo()
                {
                    CompanyName = "测试数据",
                };
                db.Insertable<CompanyInfo>(company).ExecuteCommand();

                CompanyInfo info = db.Queryable<CompanyInfo>().First();
                info.CompanyName = "更新数据";
                db.Updateable<CompanyInfo>(info).ExecuteCommand();
                 
                info = db.Queryable<CompanyInfo>().First();
                info.CompanyName = "更新数据====New";
                db.Updateable<CompanyInfo>(info).ExecuteCommand();



                if (db.DbMaintenance.IsAnyTable("CompanyInfoNew", false))
                {
                    db.DbMaintenance.DropTable<CompanyInfoNew>();
                }
                db.CodeFirst.InitTables<CompanyInfoNew>();
                CompanyInfoNew companyInfo = new CompanyInfoNew()
                {
                    CompanyName = "测试数据=CompanyInfoNew",
                };
                db.Insertable<CompanyInfoNew>(companyInfo).ExecuteCommand();

                CompanyInfoNew infonew = db.Queryable<CompanyInfoNew>().First();
                info.CompanyName = "更新数据";
                db.Updateable<CompanyInfoNew>(infonew).ExecuteCommand();

                infonew = db.Queryable<CompanyInfoNew>().First();
                info.CompanyName = "更新数据====New";
                db.Updateable<CompanyInfoNew>(infonew).ExecuteCommand();

            }
        }
    }
}
